// Vite的插件必须返回给vite一个配置对象
import fs from 'fs';
import path from 'path';

function diffDirAndFile(dirFilesArr = [], basePath = "") {
  const result = {
    dirs: [],
    files: []
  }
  dirFilesArr.forEach(name => {
    const currentFileStat = fs.statSync(path.resolve(__dirname, basePath + '/' + name));
    if (currentFileStat.isDirectory()) {
      result.dirs.push(name)
    } else {
      result.files.push(name)
    }
  })
  return result;
}

function getTotalSrcDir(keyName) {
  const result = fs.readdirSync(path.resolve(__dirname, '../src'));
  const diffResult = diffDirAndFile(result, '../src');
  const resolveAliasesObj = {}; // 放的就是一个一个的别名配置 @assets
  diffResult.dirs.forEach(dirName => {
    const key = keyName + dirName;
    const absPath = path.resolve(path.resolve(__dirname, '../src' + '/' + dirName));
    resolveAliasesObj[key] = absPath;
  })

  return resolveAliasesObj;
}

export default ({
  keyName = '@'
} = {}) => {
  return {
    name: 'my-vite-aliases',
    /**
     * 
     * @param {*} config 已有的config配置 UserConfig
     * @param {*} env { mode: string, command: string } command serve (yarn dev) build (yarn build)
     * @returns 
     */
    config(config, env) {
      // 还没有执行config文件，只是将config配置文件传给你
      // config 函数可以返回一个对象，这个对象是部分的viteconfig配置（其实就是想要修改的对象
      const resolveAliasesObj = getTotalSrcDir(keyName);
      return {
        // 我们要返回一个resolve回去, 将src目录下的所有文件夹进行别名控制
        resolve: {
          alias: resolveAliasesObj,
        }
      }
    }
  }
}
